﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.Security.Principal;
using System.IO;
using System.Diagnostics;
using LogLib;
using System.Reflection;

namespace KeyboardManager
{
     internal class PipeClient
     {      
         public int id { get; private set; }

         public const string ServerName = "StartupWatchPipe";

         public const int ClientConnectTimeout = 3000;

         public string SendMessage { get; set; }

         public PipeClient(int id, string msg)
         {
             this.id = id;
             SendMessage = msg;
         }

         public void run()
         {
             try
             {
                 using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(
                     ".",
                     ServerName,
                     PipeDirection.InOut,
                     PipeOptions.None,
                     TokenImpersonationLevel.None))
                 {
                     //连接服务端
                     pipeClient.Connect(ClientConnectTimeout);
                     StreamWriter sw = new StreamWriter(pipeClient);
                     StreamReader sr = new StreamReader(pipeClient);
                     Log.WriteAsync(string.Format("Client {0} SendMessage: {1}", id, SendMessage));
                     sw.WriteLine(SendMessage);
                     sw.Flush();
                     string temp = sr.ReadLine();
                     if (!pipeClient.IsConnected)
                     {
                         Log.WriteAsync("Pipe is Broken");
                     }
                     else
                     {
                         Log.WriteAsync("replyContent:" + temp);
                         pipeClient.Close();
                     }
                 }
             }
             catch (Exception ex)
             {
                 Log.WriteException(ex.ToString());
             }
             Log.WriteAsync(string.Format("Client {0} end of conversation", id));
         }
     }
}
